<?php
namespace yan\hkecship\utils;
class Curl extends \yan\hkecship\AbstractFactory{
    private $ch;
    public function build($url){
        $this->ch = curl_init();
        curl_setopt($this->ch, CURLOPT_URL, $url );
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        return $this;
    }
    public function setPostData($data = null){
        curl_setopt ( $this->ch, CURLOPT_POSTFIELDS, $data );
        curl_setopt ( $this->ch, CURLOPT_POST, 1 );
        return $this;
    }
    public function setHeader($header = []){
        if(!empty($header) ){
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, $header);
        }
        return $this;
    }
    public function setCallBack($callBack=null){
        if(is_object($callBack)){
            $this->ch = $callBack($this->ch);
        }
        return $this;
    }
    public function run(){
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        curl_setopt($this->ch, CURLOPT_HEADER, 0);
        $response = curl_exec($this->ch);
        if( $response === false ){
            $errors = curl_error($this->ch);
            curl_close($this->ch);
            throw new \Exception($errors, 500);            
        }
        curl_close($this->ch);
        return $response;
    }
}